import {
  Text,
  View,
  StyleSheet,
  TextInput,
  Image,
  TouchableOpacity,
  Alert,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import React, { useState } from "react";
import { LinearGradient } from "expo-linear-gradient";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { useRouter } from "expo-router"; // 引入 useRouter
import useAppStateChange from "@/hooks/useAppStateChange";
import useInputWithDone from "@/hooks/useInputWithDone";
import useCaptchaCountdown from "@/hooks/useCaptchaCountdown";
import {
  getRestoreLoginPasswordVerifyFnApi,
  restoreLoginPasswordFnAPi,
} from "./api";
import { useTranslation } from "react-i18next";

import { ToastAPI } from "@/components/Toast";
export default function Forgotpsw() {
  const { t } = useTranslation();

  const router = useRouter(); // 获取路由对象
  const appState = useAppStateChange();
  const { countdown, isDisabled, handleGetCaptcha, verifyId } =
    useCaptchaCountdown(getRestoreLoginPasswordVerifyFnApi);
  const [phoneOrEmail, setPhoneOrEmail, handlePhoneOrEmailDone] =
    useInputWithDone() as any;
  const [password, setPassword, handlePasswordDone] = useInputWithDone() as any;
  const [captChaCode, setCaptChaCode, handleCaptChaCodeDone] =
    useInputWithDone() as any;

  // 验证手机号或邮箱号格式
  const [phoneOrEmailError, setPhoneOrEmailError] = useState<string | null>(
    null
  );
  const validatePhoneOrEmail = (input: string) => {
    setPhoneOrEmail(input);
    const phoneRegex = /^1[3-9]\d{9}$/;
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    const reslt = phoneRegex.test(input) || emailRegex.test(input);
    setPhoneOrEmailError(
      reslt ? null : t("forgotPassword.phone_or_email_error")
    );
  };

  // 验证密码
  const [passwordError, setPasswordError] = useState<string | null>(null);
  const validatePasswordError = (input: string) => {
    setPassword(input);
    const passwordRegex =
      /^(?=(.*[a-z]))(?=(.*[A-Z]))(?=(.*\d))(?=[\x21-\x7e]{8,16}$).*/;

    setPasswordError(
      passwordRegex.test(input) ? null : t("forgotPassword.password_error")
    );
  };

  // 处理注册逻辑
  const handleRegisteredFn = async () => {
    if (!phoneOrEmail || !password || !captChaCode) {
      ToastAPI.warning(t("forgotPassword.toast_warning_empty"));
      return;
    }
    if (passwordError || phoneOrEmailError) {
      ToastAPI.warning(t("forgotPassword.toast_warning_invalid"));
      return;
    }
    ToastAPI.loading(t("forgotPassword.toast_loading"), "center", -1);
    try {
      const res: any = await restoreLoginPasswordFnAPi({
        account: phoneOrEmail,
        newPassword: password,
        code: captChaCode,
        verifyId,
      });
      ToastAPI.close();
      if (res.code === 0) {
        Alert.alert(
          t("forgotPassword.alert_success_title"),
          t("forgotPassword.alert_success_message"),
          [
            {
              text: t("forgotPassword.alert_cancel"),
              style: "cancel",
            },
            {
              text: t("forgotPassword.alert_login"),
              onPress: () => {
                router.back();
              },
            },
          ]
        );
        return;
      }
      ToastAPI.error(res?.errMsg || t("forgotPassword.toast_error"));
    } catch (error) {
      ToastAPI.close();
    }
  };

  return (
    <PageContainer>
      {/* 使用 KeyboardAwareScrollView 包裹内容 */}
      <KeyboardAwareScrollView
        contentContainerStyle={styles.scrollContainer}
        extraHeight={100}
      >
        <View className="bg-[#000] flex-1" style={styles.main}>
          <View className="items-center flex-row h-[46px]">
            <TouchableOpacity onPress={() => router.back()}>
              <Image
                source={require("@/assets/images/return-left.png")}
                className="w-[18px] h-[18px]"
              />
            </TouchableOpacity>
          </View>
          <View>
            <Text style={styles.title}>{t("forgotPassword.title")}</Text>
            <Text className="text-[#D7D7D7] text-[16px] mt-[15px]">
              {t("forgotPassword.subtitle")}
            </Text>
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("forgotPassword.phone_or_email_label")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handlePhoneOrEmailDone}
              blurOnSubmit={true}
              placeholder={t("forgotPassword.phone_or_email_placeholder")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={phoneOrEmail}
              onChangeText={validatePhoneOrEmail}
            />
            {phoneOrEmailError && (
              <Text style={{ color: "red", fontSize: 12, marginTop: 5 }}>
                {phoneOrEmailError}
              </Text>
            )}
          </View>

          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("forgotPassword.captcha_label")}
            </Text>
            <View className="flex-row justify-between items-center bg-[#25262A] rounded-[10px] h-[50px] mt-[15px] px-[12px]">
              <TextInput
                style={[{ fontSize: 16, color: "#fff", flex: 1 }]}
                placeholder={t("forgotPassword.captcha_placeholder")}
                placeholderTextColor={"rgba(255,255,255,0.3)"}
                value={captChaCode}
                returnKeyType="done"
                onSubmitEditing={handleCaptChaCodeDone}
                blurOnSubmit={true}
                onChangeText={setCaptChaCode}
                maxLength={6}
              />
              <TouchableOpacity
                onPress={() => handleGetCaptcha(phoneOrEmail)}
                disabled={isDisabled}
              >
                <Text className="text-[#6FC2FA] w-[80px]">
                  {countdown > 0
                    ? `${countdown}s后重试`
                    : t("forgotPassword.get_captcha")}
                </Text>
              </TouchableOpacity>
            </View>
          </View>
          <View>
            <Text className="mt-[22px] text-[#D7D7D7] text-[16px]">
              {t("forgotPassword.new_password_label")}
            </Text>
            <TextInput
              style={[
                styles.input,
                { fontSize: 16, padding: 12, color: "#fff" },
              ]}
              returnKeyType="done"
              onSubmitEditing={handlePasswordDone}
              blurOnSubmit={true}
              placeholder={t("forgotPassword.new_password_placeholder")}
              placeholderTextColor={"rgba(255,255,255,0.3)"}
              value={password}
              secureTextEntry
              onChangeText={validatePasswordError}
            />
            {passwordError && (
              <Text style={{ color: "red", fontSize: 12, marginTop: 5 }}>
                {passwordError}
              </Text>
            )}
          </View>

          <TouchableOpacity onPress={handleRegisteredFn}>
            <LinearGradient
              style={styles.loginBtn}
              colors={["#3D7FFF", "#6FC2FA"]}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 0 }}
            >
              <Text className="text-[#fff] text-[16px]">
                {t("forgotPassword.submit_button")}
              </Text>
            </LinearGradient>
          </TouchableOpacity>
        </View>
      </KeyboardAwareScrollView>
    </PageContainer>
  );
}

const styles = StyleSheet.create({
  scrollContainer: {
    flexGrow: 1, // 使内容能够伸展
    justifyContent: "center", // 中心对齐
  },
  main: {
    paddingLeft: 13,
    paddingRight: 13,
  },

  title: {
    fontSize: 24,
    color: "#fff",
    fontWeight: 600,
    paddingTop: 53,
  },
  input: {
    height: 50,
    backgroundColor: "#25262A",
    borderRadius: 10,
    marginTop: 15,
  },
  loginBtn: {
    height: 50,
    borderRadius: 10,
    justifyContent: "center",
    alignItems: "center",
    marginTop: 22,
  },
});
